<template>
  <div class="heatmap-container">
    <el-upload
      :key="uploadKey"
      class="upload-demo"
      action=""
      :auto-upload="false"
      :on-change="handleFileChange"
      :show-file-list="false"
      :accept="'.csv'"
      :disabled="isLoading"
      :limit="1"
      :before-upload="beforeUpload"
    >
      <el-button type="primary" :loading="isLoading">
        {{ isLoading ? '处理中...' : '选择CSV文件' }}
        </el-button>
      <template #tip>
        <div class="el-upload__tip">
          请上传CSV格式文件 {{ rawData ? '(当前已有数据)' : '' }}
        </div>
      </template>
    </el-upload>

    <div class="chart-container">
      <div class="heatmap" ref="heatmapRef">
        <div class="coordinate-lines">
          <div class="vertical-line"></div>
          <div class="horizontal-line"></div>
        </div>
        <div class="y-axis">
          <!-- <span>100</span>
          <span>0</span>
          <span>-100</span> -->
        </div>
        <div class="heatmap-center">
          <div v-for="(row, i) in processedData" :key="i" class="heatmap-row">
            <div v-for="(value, j) in row" :key="j" class="heatmap-cell" :style="{ backgroundColor: getColor(value) }" :title="`值: ${value}`"></div>
          </div>
        </div>
        <div class="x-axis">
          <!-- <span>-200</span>
          <span>0</span>
          <span>200</span> -->
        </div>
      </div>
      
      </div>
      <div class="color-scale">
        <div class="scale-gradient"></div>
        <div class="scale-labels">
          <span>0</span>
          <span>5</span>
          <span>9</span>
        </div>
      </div>
    </div>
  </template>
  
<script>
import { ref, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  setup() {
    const rawData = ref(null)
    const isLoading = ref(false)
    const uploadKey = ref(0)

    const processedData = computed(() => {
      if (!rawData.value || !rawData.value.length) return []
      
      const totalRows = rawData.value.length
      
      if (totalRows < 30) {
        ElMessage.warning('数据行数不足，无法处理')
        return []
      }

      return rawData.value.map(row => {
        const leftPadding = Array(6).fill(0)
        const rightPadding = Array(6).fill(0)
        return [...leftPadding, ...row, ...rightPadding]
      })
    })

    const getColor = (value) => {
      if (value === undefined || value === null) return '#FFFFFF'
      
      const colors = [
        '#FFF5F0', // 0
        '#FEE0D2', // 1
        '#FCBBA1', // 2
        '#FC9272', // 3
        '#FA6A4A', // 4
        '#EF3B2C', // 5
        '#CB181D', // 6
        '#A50F15', // 7
        '#67000D'  // 8
      ]
      
      const index = Math.min(Math.floor(value), colors.length - 1)
      return colors[index]
    }

    const beforeUpload = (file) => {
      const isCSV = file.name.endsWith('.csv')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isCSV) {
        ElMessage.error('只能上传 CSV 文件!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB!')
        return false
      }
      return true
    }

    const handleFileChange = async (file) => {
      if (!file) {
        ElMessage.warning('请选择文件')
        return
      }
  
      isLoading.value = true
      try {
        const formData = new FormData()
        formData.append('file', file.raw)
        
        const response = await axios.post(
          '/angleProfile/upload',
          formData,
          {
            headers: { 'Content-Type': 'multipart/form-data' },
            timeout: 30000
          }
        )
        
        if (response.data && Array.isArray(response.data)) {
          if (response.data.length < 30) {
            throw new Error('数据行数不足，需要至少30行数据')
          }
          
          rawData.value = response.data
          ElMessage.success(`文件 ${file.name} 处理成功，已在数据两侧各添加6列0值`)
        } else {
          throw new Error('返回的数据格式不正确')
        }
      } catch (error) {
        console.error('文件处理失败:', error)
        ElMessage.error(
          error.response?.data?.message || 
          error.message || 
          '文件处理失败，请重试'
        )
        rawData.value = null
      } finally {
        isLoading.value = false
        uploadKey.value++
      }
    }

    return {
      rawData,
      processedData,
      isLoading,
      uploadKey,
      handleFileChange,
      beforeUpload,
      getColor
    }
  }
}
</script>

<style scoped>
/* 在项目的全局 CSS 中添加 */
html, body {
  margin: 0;
  padding: 0;
}

/* 强制所有元素无间隙 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  border-spacing: 0;
}
.heatmap-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2vh;
}

.chart-container {
  position: relative;
  width: 90%;
  max-width: 800px;
  aspect-ratio: 3/2;
  background-color: #FFFFFF;
  border: 1px solid #ddd;
  margin: 2vh auto;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: visible;
}

.heatmap {
  position: relative;
  width: 90%;
  height: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0;
  line-height: 0;
}

.coordinate-lines {
  position: absolute;
  width: 90%;
  height: 90%;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 3;
  pointer-events: none;
}

.vertical-line {
  position: absolute;
  left: 50%;
  height: 100%;
  width: 1px;
  background-color: #000;
  transform: translateX(-50%);
}

.horizontal-line {
  position: absolute;
  top: 50%;
  width: 100%;
  height: 1px;
  background-color: #000;
  transform: translateY(-50%);
}

.heatmap-center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%) scale(3);
  display: block;
  font-size: 0;
  line-height: 0;
  letter-spacing: -1px;
  word-spacing: -1px;
  white-space: nowrap;
  z-index: 2;
  transform-origin: center center;
}

.heatmap-row {
  display: block;
  height: 2.5px;
  margin: 0;
  padding: 0;
  font-size: 0;
  line-height: 0;
  white-space: nowrap;
}

.heatmap-cell {
  width: 8.8px;
  height: 2.5px;
  display: inline-block;
  margin: 0 !important;
  padding: 0 !important;
  border: 0 !important;
  vertical-align: top;
  font-size: 0;
  line-height: 0;
}

.y-axis {
  position: absolute;
  left: 0;
  height: 90%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
  transform: translateX(-3em);
}

.y-axis span {
  font-size: clamp(12px, 1.2vw, 16px);
  font-weight: bold;
}

.x-axis {
  position: absolute;
  bottom: 0;
  width: 90%;
  display: flex;
  justify-content: space-between;
  transform: translateY(3em);
}

.x-axis span {
  font-size: clamp(12px, 1.2vw, 16px);
  font-weight: bold;
}

.color-scale {
  position: absolute;
  top: 0;
  right: 0;
  width: 20%;
  min-width: 100px;
  transform: translate(0, -120%);
}

.scale-gradient {
  width: 100%;
  height: 20px;
  background: linear-gradient(to right, 
    #FFF5F0,
    #FEE0D2,
    #FCBBA1,
    #FC9272,
    #FA6A4A,
    #EF3B2C,
    #CB181D,
    #A50F15,
    #67000D
  );
  border-radius: 4px;
  margin: 4px 0;
}

.scale-labels {
  display: flex;
  justify-content: space-between;
  width: 100%;
  font-size: clamp(10px, 1vw, 14px);
  font-weight: bold;
}

.upload-demo {
  margin: 2vh 0;
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-upload__tip {
  margin-top: 1vh;
  font-size: clamp(12px, 1vw, 14px);
}
  </style>